import json

from django.http import JsonResponse
from django.views import View
from rest_framework.generics import ListAPIView, UpdateAPIView, GenericAPIView
from rest_framework.mixins import UpdateModelMixin
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from goods.models import SKU
from meiduo_admin.serializers.order import OrderInfoSerializer, OrderInfolitterSerializer, SKUSerializer, \
    OrderGoodsSerializer, OrderStatusSerializer
from meiduo_admin.utils import PageNum
from orders.models import OrderInfo, OrderGoods


class OrderInfoView(ModelViewSet):
    serializer_class = OrderInfolitterSerializer
    pagination_class = PageNum

    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')

        if keyword:
            return OrderInfo.objects.filter(order_id__contains=keyword)
        else:
            return OrderInfo.objects.all()


class OrderDetailView(ListAPIView):
    serializer_class = OrderInfoSerializer

    def get_queryset(self):
        pk = self.kwargs['pk']
        # return OrderInfo.objects.all()
        return OrderInfo.objects.filter(order_id=pk)


# class OrderStatusView(GenericAPIView):
#     queryset = OrderInfo.objects.all()
#     serializer_class = OrderStatusSerializer
#
#     def put(self, request, order_id):
#
#         order = self.get_object()
#         serializer = self.get_serializer(instance=order, data=request.data)
#
#         # serializer = OrderInfo.objects.filter(order_id=order_id).update(status=status)
#
#         if serializer.is_valid():
#             serializer.save()
#
#             return Response(serializer.data)
#         else:
#             return Response({'msg': '错误信息'})


class OrderStatusView(View):
    '''订单状态修改'''

    def put(self, request, order_id):
        status = json.loads(request.body.decode()).get('status')
        try:
            OrderInfo.objects.filter(order_id=order_id).update(status=status)
        except Exception as e:
            return Response({'msg': '操作失败'})
        return JsonResponse({
            "order_id": order_id,
            "status": status
        })
